package com.rpp.study.controller;

import org.apache.dubbo.config.annotation.Service;
import com.rpp.study.base.LagouResponse;
import com.rpp.study.service.EmailApiService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description
 * @Author rpp
 * @Date 2020/8/28 10:49 下午
 */
@Service
@RestController
@RequestMapping(value = "/api/email")
public class EmailController implements EmailApiService {

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 发送验证码到邮箱，true成功，false失败
     *
     * @param email
     * @return
     */
    @Override
    @PostMapping(value = "/send/{email}/{code}", consumes = MediaType.APPLICATION_JSON_VALUE)
    public LagouResponse<Boolean> sendEmail(@PathVariable("email") String email,
                                            @PathVariable("code") String code) {
        if (StringUtils.isBlank(email)) {
            return LagouResponse.error(false, "邮箱不能为空");
        }
        if (StringUtils.isBlank(code)) {
            return LagouResponse.error(false, "验证码不能为空");
        }
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("704729018@qq.com");
            message.setTo(email);
            message.setSubject("注册验证码");
            message.setText(code);
            javaMailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            return LagouResponse.error(false, "验证码发送异常：" + e.getMessage());
        }
        return LagouResponse.success(true);
    }
}
